/*
 * Copyright (c) 2022 86188
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bei.lingluan.utils;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.app.Context;
import ohos.net.NetCapabilities;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

/**
 * @author 北海
 * @version 1.0
 * @description Network connection help class
 * @date 2022/2/14
 */
public class NetConnectHelper {

    /**
     *
     * @param context
     * @return true表示网络连接，false表示网络未连接
     */
    public static boolean isNetworkConnectedInternet(Context context) {
        NetManager netManager = NetManager.getInstance(context);
        NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
        // NetCapabilities.NET_CAPABILITY_VALIDATED表示连接了网络，并且可以上网
        return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED);
    }

    /**
     * 实时监听网络状态
     * @author 北海
     */
    public void netStatus(Context context, AbilitySlice abilitySlice, Component component){
        NetManager netManager = NetManager.getInstance(context);
        //获取实时的网络状态
        NetStatusCallback callback = new NetStatusCallback() {
            //网络连接成功
            @Override
            public void onAvailable(NetHandle handle) {
                super.onAvailable(handle);

                //在UI线程中进行页面组件的调整
                abilitySlice.getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        //
                    }
                });
            }
            //网络断开连接
            @Override
            public void onLost(NetHandle handle) {
                super.onLost(handle);

                abilitySlice.getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        //
                    }
                });
            }
        };
        //监听实时的网络状态
        netManager.addDefaultNetStatusCallback(callback);
    }

}
